package com.smarttest.common.util;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.zip.GZIPInputStream;

public class APIRequestUtil {
	private static String apiUrl ="http://api.huoyunren.com/router/rest";
	public static int version = -1;
	public static String getResultDefUrl(String method, Object... params) {
		return getResult(apiUrl, method, params);
	}
	public static String getResult(String url, String method, Object... params) {
        Map<Object,Object> map = new HashMap<Object,Object>();
        for (int i = 0; i < params.length; i += 2) {
            map.put(params[i], params[i + 1]);
        }
        if(version > 0){
        	map.put("version", version);
        }
        map.put("app_key", "1089");
        map.put("method", method);
        map.put("format", "json");
        map.put("timestamp", df.format(new Date(System.currentTimeMillis())));
        String sign = sign(map, "ss92mvc743n1");
        map.put("sign", sign);
        String result = createRequestParam(map);
        result = getResult(url, result);
        return result;
    }
    
	private static final SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	private static String createRequestParam(Map<Object, Object> map) {
		StringBuilder param = new StringBuilder();
		for (Entry<Object, Object> en : map.entrySet()) {
			Object value = en.getValue();
			if (value != null) {
				try {
					value = URLEncoder.encode(value.toString(), "utf-8");
				} catch (UnsupportedEncodingException ex) {
				}
				param.append("&").append(en.getKey().toString()).append("=").append(value);
			}
		}
		return param.toString().substring(1);
	}
	
	/*
	 * 二行制转字符串
	 */
	private static String byte2hex(byte[] b) {
		StringBuffer hs = new StringBuffer();
		String stmp = "";
		for (int n = 0; n < b.length; n++) {
			stmp = (java.lang.Integer.toHexString(b[n] & 0XFF));
			if (stmp.length() == 1)
				hs.append("0").append(stmp);
			else
				hs.append(stmp);
		}
		return hs.toString().toUpperCase();
	}

	/*
	 * 签名方法，用于生成签名。
	 * 
	 * @param params 传给服务器的参数
	 * 
	 * @param secret 分配给您的APP_SECRET
	 */
	private static String sign(Map<Object,Object> params, String secret) {
		String result = null;
		if (params == null)
			return result;

		// 将参数按key排序
		Set<Object> keys = params.keySet();
		String[] ps = new String[keys.size()];
		int i = 0;
		for (Object key : keys) {
			Object value = params.get(key);
			if (value != null) {
				ps[i++] = key + value.toString();
			}
		}
		if (i == 0)
			return result;
		String[] ss = new String[i];
		System.arraycopy(ps, 0, ss, 0, i);
		Arrays.sort(ss);
		
		// 将secret同时放在头尾，拼成字符串
		StringBuilder orgin = new StringBuilder(secret);
		for (int j = 0; j < ss.length; j++) {
			orgin.append(ss[j]);
		}
		orgin.append(secret);
		
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			result = byte2hex(md.digest(orgin.toString().getBytes("utf-8")));
		} catch (Exception ex) {
			throw new java.lang.RuntimeException("sign error !");
		}
		return result;
	}

	/*
	 * 得到返回的内容
	 */
	private static String getResult(String urlStr, String content) {
		URL url = null;
		HttpURLConnection connection = null;
		String result = null;

		try {
			url = new URL(urlStr);
			connection = (HttpURLConnection) url.openConnection();
			connection.setDoOutput(true);
			connection.setDoInput(true);
			connection.setRequestMethod("POST");
			connection.setUseCaches(false);
			connection.setRequestProperty("Accept-Encoding", "gzip");
			connection.connect();
			DataOutputStream out = new DataOutputStream(connection.getOutputStream());
			out.writeBytes(content);
			out.flush();
			out.close();
			
			String encoding = connection.getContentEncoding();//
			InputStream inputStream = connection.getInputStream();
			InputStreamReader is  = null;
			BufferedReader reader = null;
			if("gzip".equals(encoding)){
				is = new InputStreamReader(new GZIPInputStream(inputStream), "UTF-8");
				reader = new BufferedReader(is);
			}else{
				is = new InputStreamReader(inputStream, "UTF-8");
				reader = new BufferedReader(is);
			}
			if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
				StringBuffer buffer = new StringBuffer();
				String line = "";
				while ((line = reader.readLine()) != null) {
					buffer.append(line);
				}
				reader.close();
				result = buffer.toString();
			} else {
				System.out.println("url:"+urlStr+",ResponseCode:"+connection.getResponseCode()+",ResponseMessage:"+connection.getResponseMessage());
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (connection != null) {
				connection.disconnect();
			}
		}
		return result;
	}
}
